package com.luweiteng.valiteddemo.exception;

import com.luweiteng.valiteddemo.entity.BaseResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author ludans
 * @program valited-demo
 * @date 2020/8/8 16:26
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.luweiteng.valiteddemo.controller")
public class GlobalHandler {


    /**
     * 请求方式不对
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public BaseResp handleException(HttpRequestMethodNotSupportedException e) {
        return BaseResp.fail("不支持' " + e.getMethod() + "'请求");
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResp notFound(RuntimeException e) {
        log.error("运行时异常:", e);
        return BaseResp.fail(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public BaseResp handleException(Exception e) {
        log.error(e.getMessage(), e);
        return BaseResp.fail("服务器异常，请联系管理员");
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResp validationHandler(MethodArgumentNotValidException e) {
        return getBaseRespError(e.getBindingResult());
    }

    private BaseResp getBaseRespError(BindingResult bindingResult2) {
        BindingResult bindingResult = bindingResult2;
        String errorMsg = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMsg += fieldError.getDefaultMessage() + "!";
        }
        log.error("错误信息:{}", errorMsg);
        return BaseResp.fail(errorMsg);
    }

    @ExceptionHandler(value = BindException.class)
    public BaseResp validationExceptionHandler(BindException e) {
        return getBaseRespError(e.getBindingResult());
    }



    /**
     * 校验异常
     */
    
    @ExceptionHandler(value = ConstraintViolationException.class)
    public BaseResp ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        List<String> msgList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConstraintViolation<?> cvl = iterator.next();
            msgList.add(cvl.getMessageTemplate());
        }
        return BaseResp.fail(String.join(",",msgList));
    }

}
